package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.CeAgentAccountDao;
import com.jy.admin.db.dao.CeCommentPushLogDao;
import com.jy.admin.db.dao.CeMerchantDao;
import com.jy.admin.db.dao.CeOrdersDetailDao;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class JituService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JituService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    private String verifyKey = "";


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("jitu", this);
    }


    private String generateTM() {
        char[] cha = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
                '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuilder tm = new StringBuilder();
        for (int i = 0; i < 999; i++) {
            int index;
            index = (int) (Math.random() * (cha.length));
            char c = cha[index];
            if (!tm.toString().contains(c + "")) {
                tm.append(c);
            }
            if (tm.length() == 20) {
                LOGGER.info("====,i:{}", i);
                break;
            }
        }
        return tm.toString();
    }

    private String generateCode() {
        char[] cha = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
                '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuilder tm = new StringBuilder();
        for (int i = 0; i < 999; i++) {
            int index;
            index = (int) (Math.random() * (cha.length));
            char c = cha[index];
            if (!tm.toString().contains(c + "")) {
                tm.append(c);
            }
            if (tm.length() == 8) {
                LOGGER.info("====,i:{}", i);
                break;
            }
        }
        return tm.toString();
    }


    public byte[] getCaptchakey(String merchantCode) {
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(merchantCode);
        verifyKey = generateCode();
        String url = ceMerchantEntity.getApiDomain() + "/d/modulerole/admin/verificationCode?verifyKey=" + verifyKey;
        Map<String, String> headers = Maps.newHashMap();
        headers.put("tm", generateTM());
        byte[] result = HttpUtil.postPageRes(url, headers, "");

        return result;
    }

    public String login(CeAgentAccountEntity agentAccount, String verificationCode) {
        if (!verifyKey.equals("")) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/d/modulerole/admin/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> header = Maps.newHashMap();
            header.put("Content-Type", "application/json");
            header.put("tm", generateTM());
            JSONObject params = new JSONObject();
            params.put("loginName", agentAccount.getAccount());
            params.put("password", agentAccount.getPassword());
            params.put("verificationCode", verificationCode);
            params.put("verifyKey", verifyKey);
            String result = HttpUtil.postPageBody(url, header, params.toString());
            LOGGER.info("== 请求登录接口 ==,result:{}", result);
            if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
                LOGGER.error("== 请求登录接口 成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("token", JsonIterator.deserialize(result).get("data").get("token").toString());
                requestHeader.put("Cookie", "language=en; sidebarStatus=1; Admin-Token=" + JsonIterator.deserialize(result).get("data").get("token").toString());
                requestHeader.put("tm", generateTM());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return result;
            }
        }
        return "登录失败";
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/business/app_packages/index?addtabs=1&sort=id&order=desc&offset=0&limit=10&filter={\"status\":[\"normal\",\"hidden\"]}&op={\"status\":\"in\"}";
        LOGGER.info("== 开始检测Token是否有效 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        String result = HttpUtil.getPageSSL(url, Maps.newHashMap(),headers);
        LOGGER.info("== 结束检测Token是否有效 ==,result:{}", result);

        if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("code").toString())) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.user_info.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }
        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== InfinityCashService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }


    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/business/order_details/urge_orders?addtabs=1&sort=id&order=desc&offset=0&limit=1000";
        LOGGER.info("== 开始请求未还款订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String result = HttpUtil.getPageSSL(url, params, headers);
        if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("code").toString())) {
            LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }
        List<Any> resultsList = JsonIterator.deserialize(result).get("rows").asList();

        LOGGER.info("== 未还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));
        LOGGER.info("== 未还款订单列表数量 ==,agentCode:{},size:{}", agentAccount.getAgentCode(), resultsList.size());


        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，agentCode:{},size:{}", agentAccount.getAgentCode(), activeOrders.size());

        //对比订单数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("== 存在未拉取订单 ==，agentCode:{},size:{}", agentAccount.getAgentCode(), resultsList.size());
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("order_no").toString();
                    CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (todayOneByOrderNo == null) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},loanId:{}", agentAccount.getAgentCode(), item.get("loanAppId").toString(), e);
                }
            });
        } else {
            resultsList.forEach(item -> {
                try {
                    String orderNo = item.get("order_no").toString();
                    CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                    if (OneByOrderNo == null) {
                        LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(orderNo)
                                .setOrderInfo(item.toString())
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    } else {
                        LOGGER.info("== 订单已存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
                }
            });

            LOGGER.info("== 订单更新 ==，size:{}", resultsList.size());
            activeOrders.forEach(item -> {
                try {
                    String id = JsonIterator.deserialize(item.getOrderInfo()).get("order_no").toString();
                    boolean hasOrder = false;
                    for (Any child : resultsList) {
                        String orderNo = child.get("order_no").toString();
                        if (id.equals(orderNo)) {
                            LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                            hasOrder = true;
                            break;
                        }

                    }
                    if (!hasOrder) {
                        LOGGER.info("== 当前订单不存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), id);
                        if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            item.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(item);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
                }
            });

        }
        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        headers.remove("X-Requested-With");
        Map<String, String> contactHeaders = getHeaders(agentAccount);
        HashMap<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();
                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());

                String userId = orderInfo.get("user_id").toString();
                String orderId = orderInfo.get("order_id").toString();
                String repaymentInfoUrl = merchant.getApiDomain() + "/order/orders/view?ids=" + orderId + "&addtabs=1";

                String repaymentInfo = HttpUtil.getPageSSL(repaymentInfoUrl, params, headers);
                LOGGER.info("== 获取成功 repaymentInfo==");

                Document document = Jsoup.parse(repaymentInfo);
                Elements tables = document.select("div");
                if (tables.size() <= 0) {
                    return;
                }
                JSONObject detail = new JSONObject();
                for (int i = 0; i < tables.size(); i++) {
                    String className = tables.get(i).attributes().getIgnoreCase("class");
                    if (!className.equals("list")) {
                        continue;
                    }
                    Document document1 = Jsoup.parse(tables.get(i).html());
                    Elements tables1 = document1.select("div");
                    Document document2 = Jsoup.parse(tables1.html());
                    Elements tables2 = document2.select("p");
                    String key = "";
                    String conditions = tables2.get(0).childNodes().get(0).toString();

                    if (conditions.equals("Order number")) {
                        key = "orderNo";
                    } else if (conditions.equals("Phone number")) {
                        key = "phone";

                    } else if (conditions.equals("Apply for a product")) {
                        key = "productName";

                    } else if (conditions.equals("Whether to refinance")) {
                        key = "isOldLoan";

                    } else if (conditions.equals("Loan amount")) {
                        key = "loanAmount";

                    } else if (conditions.equals("Loan term")) {
                        key = "loanTerm";

                    } else if (conditions.equals("Amount received")) {
                        key = "receivedAmount";

                    } else if (conditions.equals("Amount due")) {
                        key = "dueAmount";

                    } else if (conditions.equals("Order status")) {
                        key = "orderStatus";

                    } else if (conditions.equals("Days Overdue")) {
                        key = "overdueDays";

                    } else if (conditions.equals("Overdue amount")) {
                        key = "overdueAmount";

                    } else if (conditions.equals("Application time")) {
                        key = "applicationTime";

                    } else if (conditions.equals("Review time")) {
                        key = "reviewTime";

                    } else if (conditions.equals("Loan time")) {
                        key = "loanTime";

                    } else if (conditions.equals("Repayment time")) {
                        key = "repaymentTime";

                    } else if (conditions.equals("Complete time")) {
                        key = "completeTime";
                    }
                    String value = "";
                    if (tables2.get(1).childNodes().size() > 0) {
                        value = tables2.get(1).childNodes().get(0).toString();
                    }
                    detail.put(key, value);
                }
                infoMap.put("repaymentInfo", detail.toString());

                String remainMoney = detail.getString("dueAmount");
                updateRemainMoney(order.getCollectionNo(), remainMoney);

                String baseInfoUrl = merchant.getApiDomain() + "/user/user/view/ids/" + userId + "?order_id=" + orderId;

                String baseInfo = HttpUtil.getPageSSL(baseInfoUrl, params, headers);
                LOGGER.info("== 获取成功 repaymentInfo==");

                Document baseDocument = Jsoup.parse(baseInfo);
                Elements ImgTables = baseDocument.select("img");
                if (ImgTables.size() <= 0) {
                    return;
                }
                List<String> images = Lists.newArrayList();
                for (int i = 0; i < ImgTables.size(); i++) {
                    String src = ImgTables.get(i).attributes().getIgnoreCase("src");
                    images.add(src);
                }
                LOGGER.info("== 获取成功 images==");
                infoMap.put("images", JsonStream.serialize(images));
                updateImages(order.getOrderNo(),JsonStream.serialize(images), order.getMerchantCode());

                Elements baseTables = baseDocument.select("div");
                if (baseTables.size() <= 0) {
                    return;
                }

                JSONObject baseDetail = new JSONObject();
                JSONArray contacts = new JSONArray();
                for (int i = 0; i < baseTables.size(); i++) {
                    String className = baseTables.get(i).attributes().getIgnoreCase("class");
                    if (className.equals("list")) {
                        Document document1 = Jsoup.parse(baseTables.get(i).html());
                        Elements tables1 = document1.select("div");
                        Document document2 = Jsoup.parse(tables1.html());
                        Elements tables2 = document2.select("p");
                        String key = "";
                        String conditions = tables2.get(0).childNodes().get(0).toString();
                        if (conditions.equals("Name")) {
                            key = "name";
                        } else if (conditions.equals("Gender")) {
                            key = "gender";

                        } else if (conditions.equals("Aadhaar NO")) {
                            key = "aadhaarNO";

                        } else if (conditions.equals("Pan Card NO")) {
                            key = "panCardNO";

                        } else if (conditions.equals("Date of birth")) {
                            key = "birthDay";

                        } else if (conditions.equals("E-mail")) {
                            key = "email";

                        } else if (conditions.equals("Document address")) {
                            key = "address";

                        }
                        String value = "";
                        if (tables2.get(1).childNodes().size() > 0) {
                            value = tables2.get(1).childNodes().get(0).toString();
                        }
                        if (StringUtils.isNotEmpty(key)) {
                            baseDetail.put(key, value);
                        }
                    }else if (className.equals("til itxt")){
                        JSONObject object = new JSONObject();
                        Document document1 = Jsoup.parse(baseTables.get(i).html());
                        Elements tables1 = document1.select("div");
                        object.put("name",tables1.get(1).childNodes().get(0).toString().replace("\n","").replace("&nbsp;",""));
                        object.put("phone",tables1.get(2).childNodes().get(0).toString().replace("\n","").replace("&nbsp;","").replaceAll(" ",""));
                        contacts.add(object);
                    }
                }
                infoMap.put("baseInfo", baseDetail.toString());
                infoMap.put("contactInfo", contacts.toString());

                LOGGER.info("==contacts==,contacts:{}", contacts.toString());
                LOGGER.info("==baseInfo==,baseDetail:{}", baseDetail.toString());


                if (!hasDetailData) {
                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {

                        String contactInfoUrl = merchant.getApiDomain() + "/user/reports/phone_book?addtabs=1&sort=user_id&order=desc&offset=0&limit=500&filter={\"user_id\":\""+userId+"\"}&op={\"user_id\":\"=\"}";
                        String contactInfo = HttpUtil.getPageSSL(contactInfoUrl,params, contactHeaders);
                        LOGGER.info("== 获取成功 contactInfo==");

                        try {
                            List<Any> list = JsonIterator.deserialize(contactInfo).get("rows").asList();

                            JSONObject jsonData = new JSONObject();
                            JSONArray contactsList = new JSONArray();
                            for (Any vo : list) {
                                JSONObject j1 = new JSONObject();
                                j1.put("name", vo.get("contact_display_name").toString().equals("") ? "no" : vo.get("contact_display_name").toString());
                                String phone = vo.get("number").toString();
                                if (!phone.equals("") && phone.length() > 9) {
                                    if (phone.contains("+91")) {
                                        phone = phone.replace("+91", "");
                                        phone = phone.replaceAll(" ", "");
                                    }
                                    j1.put("phone", phone);
                                    contactsList.add(j1);
                                }
                            }
                            jsonData.put("contacts", contactsList.toString());

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("user").get("app_name")+"["+orderDetail.get("orders").get("product_name").toString()+"]";
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setAccount_id(agentAccount.getId())
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String borrowCapital = repaymentInfo.get("loanAmount").toString();
                String actualAmount = repaymentInfo.get("receivedAmount").toString();
                String paidAmount = "0";
                String remianAmount = new BigDecimal(repaymentInfo.get("dueAmount").toString()).add(new BigDecimal( repaymentInfo.get("overdueAmount").toString())).toString();
                String repaymentAmount = new BigDecimal(repaymentInfo.get("dueAmount").toString()).add(new BigDecimal( repaymentInfo.get("overdueAmount").toString())).toString();
                String overdueDays = repaymentInfo.get("overdueDays").toString();
                String serviceFee = "0";
                String lateFee = repaymentInfo.get("overdueAmount").toString();
                int loanType = repaymentInfo.get("isOldLoan").toString().equalsIgnoreCase("Yes")?2:1;
                String overdueRatio = "0";
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
                }
                String receivedDate = StringUtils.isNotEmpty(repaymentInfo.get("loanTime").toString())?DateUtil.getDate(DateUtil.getDate(repaymentInfo.get("loanTime").toString(), "dd/MM/yyyy"), "yyyy-MM-dd"):DateUtil.getDate(DateUtil.getDate(repaymentInfo.get("applicationTime").toString(), "dd/MM/yyyy"), "yyyy-MM-dd");
                String repaymentDate = DateUtil.getDate(DateUtil.getDate(repaymentInfo.get("repaymentTime").toString(), "dd/MM/yyyy"), "yyyy-MM-dd");
                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(loanType)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setAppLink("")
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(receivedDate)
                        .setRepaymentDate(repaymentDate)
                        .setRemainMoney(remianAmount)
                        .setTotalMoney(repaymentAmount);

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = personalInfoJson.get("aadhaarNO").toString();
                String pancardNo = personalInfoJson.get("panCardNO").toString();
                String email = personalInfoJson.get("email").toString();
                String name = personalInfoJson.get("name").toString();
                String mobile = repaymentInfo.get("phone").toString();
                String pinCode = "no";
                int gender = "male".equalsIgnoreCase(personalInfoJson.get("gender").toString()) ? 1 : 0;
                int maritalStatus = 0;
                int education = 0;
                String address = personalInfoJson.get("address").toString();
                String state = "no";
                String city = "no";
                String birthDay = "";
                if (!personalInfoJson.get("birthDay").toString().equals("")) {
                    birthDay = DateUtil.getDate(DateUtil.getDate(personalInfoJson.get("birthDay").toString(), "dd/MM/yyyy"), "yyyy-MM-dd");
                } else {
                    birthDay = DateUtil.getDate("yyyy-MM-dd");
                }

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("phone").toString();
                    friendName = contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("phone").toString();
                }


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        waitingPaidCheckOrders.forEach(order -> {
//            String orderNo = order.getOrderNo();
//            String repaymentUrl = merchant.getApiDomain() + "/d/order/loan/details/info";
//            headers.replace("tm", generateTM());
//            String repaymentResult = HttpUtil.postPageBody(repaymentUrl, headers, orderNo);
//            LOGGER.info("== 开始请求订单详情 ==,url:{}", repaymentUrl);
//            if (!JsonIterator.deserialize(repaymentResult).get("code").toString().equals("200")) {
//                LOGGER.info("== 获取订单详情失败，token失效,account:{}", agentAccount.getAgentCode());
//                return;
//            }
//            LOGGER.info("== 获取成功 repaymentInfo==");
//            Any currentOrder = JsonIterator.deserialize(repaymentResult).get("data");
//
//            String remainMoney = currentOrder.get("residueAmount").toString();
//            if (!remainMoney.equals("0")) {
//                LOGGER.info("== 还款金额 remainMoney==,remainMoney:{},orderNo:{}", remainMoney, orderNo);
//            }
//            updateRemainMoney(order.getCollectionNo(), remainMoney);
//
//            if (currentOrder.get("orderStatus").toString().equals("INFINISH") || currentOrder.get("orderStatus").toString().equals("INOK")) {//status:INFINISH为正常结清，INOK为平账结清
//                LOGGER.info("== 订单已还款 ==,OrderNo:{},repayState:{}", order.getOrderNo(), currentOrder.get("orderStatus").toString());
//                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
//                order.setStatus(OrderStatusEnum.paid_update.getStatus());
//                ordersDao.updateByPrimaryKey(order);
//                return;
//            }
//
//            if (currentOrder.get("orderStatus").toString().equals("INWAIT") && currentOrder.get("repaymentStatus").toString().contains("展期还款")) {//status:订单状态为INWAIT，还款状态显示展期还款中是展期订单
//                LOGGER.info("== 订单已展期 ==,OrderNo:{},orderStatus:{},repaymentStatus:{}", order.getOrderNo(), currentOrder.get("orderStatus").toString(), currentOrder.get("repaymentStatus").toString());
//                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
//                order.setStatus(OrderStatusEnum.paid_update.getStatus());
//                ordersDao.updateByPrimaryKey(order);
//                return;
//            }
//
//            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
//
//
//            order.setStatus(OrderStatusEnum.removed.getStatus());
//            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
//            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = new BigDecimal(repaymentInfo.get("dueAmount").toString()).add(new BigDecimal( repaymentInfo.get("overdueAmount").toString())).toString();

                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : new BigDecimal(repaymentInfo.get("paidAmount").toString()).divide(new BigDecimal(100)).toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

//        JiTuCollectionTagEnum currentTag = JiTuCollectionTagEnum.RNR_V2;
//
//        for (JiTuCollectionTagEnum e : JiTuCollectionTagEnum.values()) {
//            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
//                currentTag = e;
//            }
//        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getTodayOneByOrderNoAndAgentCode(ceCommentPushLogEntity.getOriginNo(), account.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
//        try {
//            Map<String, String> headers = getHeaders(account);
//            headers.replace("tm", generateTM());
//            JSONObject params = new JSONObject();
//            params.put("orderId", ceOrdersEntity.getOrderNo());
//            params.put("collectionRemark", currentTag.getShortDesc());
//            params.put("crawlName", orderInfo.get("customerName").toString());
//            params.put("crawlPhone", orderInfo.get("phone").toString());
//            params.put("crawlRelation", "self");
//            params.put("collectionStatus", currentTag.getResult());
//            params.put("repaymentAttitude", currentTag.getRepayResult());
//            LOGGER.info("== JiTu 开始同步催记到甲方D ==,params:{}", JsonStream.serialize(params));
//            String noteUrl = ceMerchantEntity.getApiDomain() + "/d/collection/dispose/record";
//            String result = HttpUtil.postPageBody(noteUrl, headers, params.toString());
//            LOGGER.info("== JiTu 开始同步催记到甲方 ==,res:{}", result);

//            if ("200".equals(JsonIterator.deserialize(result).get("code").toString())) {
//                LOGGER.info("== 开始同步催记到甲方 success==");
//                return true;
//            } else {
//                LOGGER.error("== 开始同步催记到甲方 error==");
//            }

//        } catch (Exception e) {
//            LOGGER.error("== 开始同步催记到甲方 exception==", e);
//        }
        return true;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        String id = orderInfoJson.get("id").toString();
        String order_id = orderInfoJson.get("order_id").toString();
        Map<String, String> headers = getHeaders(accountEntity);
        headers.remove("X-Requested-With");

        String link = "No Link";
        String dialogUrl = ceMerchantEntity.getApiDomain() + "/order/payins/add?ids="+id+"&pay_type=repay&dialog=1";
        Map<String,String> params = Maps.newHashMap();
        String dialogResult = HttpUtil.getPageSSL(dialogUrl, params,headers);
        Document document = Jsoup.parse(dialogResult);

        Elements tables = document.select("input");
        if (tables.size() <= 0) {
            return link;
        }

        String value="";
        for (int i = 0; i < tables.size(); i++) {
            String className = tables.get(i).attributes().getIgnoreCase("name");
            if (className.equals("row[amount]")) {
                value = tables.get(i).attributes().getIgnoreCase("value");
            }
        }
        Map<String, String> header = getHeaders(accountEntity);
        String url = ceMerchantEntity.getApiDomain() + "/order/payins/add?ids="+id+"&order_id="+order_id+"&pay_type=repay&amount="+value;
        LOGGER.info("== 获取JiTu还款链接 ==,url:{}", url);
        String result = HttpUtil.getPageSSL(url, params,header);
        LOGGER.info("== 获取JiTu还款链接 ==,url:{},res:{}", url, result);
        if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("pay_url").toString())) {
            link = JsonIterator.deserialize(result).get("pay_url").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        }
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(accountEntity);
        headers.remove("X-Requested-With");

        String id = orderInfoJson.get("id").toString();
        String order_id = orderInfoJson.get("order_id").toString();
        String link = "No Link";
        String dialogUrl = ceMerchantEntity.getApiDomain() + "/order/payins/add?ids="+id+"&pay_type=delay&dialog=1";
        Map<String,String> params = Maps.newHashMap();
        String dialogResult = HttpUtil.getPageSSL(dialogUrl, params,headers);
        Document document = Jsoup.parse(dialogResult);

        Elements tables = document.select("input");
        if (tables.size() <= 0) {
            return link;
        }

        String value="";
        for (int i = 0; i < tables.size(); i++) {
            String className = tables.get(i).attributes().getIgnoreCase("name");
            if (className.equals("row[amount]")) {
                value = tables.get(i).attributes().getIgnoreCase("value");
            }
        }
        Map<String, String> header = getHeaders(accountEntity);

        LOGGER.info("==获取JiTu还款金额==,value:{}", value);
        String url = ceMerchantEntity.getApiDomain() + "/order/payins/add?ids="+id+"&order_id="+order_id+"&pay_type=delay&amount="+value;
        LOGGER.info("== 获取JiTu还款链接 ==,url:{}", url);
        String result = HttpUtil.getPageSSL(url, params,header);
        LOGGER.info("== 获取JiTu还款链接 ==,url:{},res:{}", url, result);
        link = JsonIterator.deserialize(result).get("return_msg").toString();
        if (StringUtils.isNotEmpty(JsonIterator.deserialize(result).get("pay_url").toString())) {
            link = JsonIterator.deserialize(result).get("pay_url").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        }
        return link;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        return "";
    }


    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return "";
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        String repaymentUrl = merchant.getApiDomain() + "/d/order/loan/details/info";
        headers.replace("tm", generateTM());
        String repaymentResult = HttpUtil.postPageBody(repaymentUrl, headers, orderNo);
        LOGGER.info("== 开始请求订单详情 ==,url:{}", repaymentUrl);
        if (!JsonIterator.deserialize(repaymentResult).get("code").toString().equals("200")) {
            LOGGER.info("== 获取订单详情失败，token失效,account:{}", agentAccount.getAgentCode());
            return "no order found";
        }
        LOGGER.info("== 获取成功 repaymentInfo==");
        Any currentOrder = JsonIterator.deserialize(repaymentResult).get("data");

        String remainMoney = currentOrder.get("residueAmount").toString();
        if (!remainMoney.equals("0")) {
            LOGGER.info("== 还款金额 remainMoney==,remainMoney:{},orderNo:{}", remainMoney, orderNo);
        }
        updateRemainMoney(ordersEntity.getCollectionNo(), remainMoney);

        if (currentOrder.get("orderStatus").toString().equals("INFINISH") || currentOrder.get("orderStatus").toString().equals("INOK")) {//status:INFINISH为正常结清，INOK为平账结清
            LOGGER.info("== 订单已还款 ==,OrderNo:{},repayState:{}", ordersEntity.getOrderNo(), currentOrder.get("orderStatus").toString());
            ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
            ordersEntity.setStatus(OrderStatusEnum.paid_update.getStatus());
            ordersDao.updateByPrimaryKey(ordersEntity);
            return "paid already!";
        }

        if (currentOrder.get("orderStatus").toString().equals("INWAIT") && currentOrder.get("repaymentStatus").toString().contains("展期还款")) {//status:订单状态为INWAIT，还款状态显示展期还款中是展期订单
            LOGGER.info("== 订单已展期 ==,OrderNo:{},orderStatus:{},repaymentStatus:{}", ordersEntity.getOrderNo(), currentOrder.get("orderStatus").toString(), currentOrder.get("repaymentStatus").toString());
            ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
            ordersEntity.setStatus(OrderStatusEnum.paid_update.getStatus());
            ordersDao.updateByPrimaryKey(ordersEntity);
            return "paid already!";
        }

        LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", orderNo);

        ordersEntity.setStatus(OrderStatusEnum.removed.getStatus());
        ordersEntity.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
        ordersDao.updateByPrimaryKey(ordersEntity);
        return "no paid";
    }

    public static void main(String[] args) {
        String detail = "{\n" +
                "    \"interest_amount\":\"0.00\",\n" +
                "    \"product_id\":10,\n" +
                "    \"interest_rate\":0,\n" +
                "    \"repaid_amount\":\"0.00\",\n" +
                "    \"id\":70959,\n" +
                "    \"reduce_amount\":\"0.00\",\n" +
                "    \"risk_result\":1,\n" +
                "    \"term_unit\":\"days\",\n" +
                "    \"urge_time\":1658975659,\n" +
                "    \"expire_time\":1658860200,\n" +
                "    \"loan_amount\":\"6000.00\",\n" +
                "    \"apply_time\":null,\n" +
                "    \"is_reloan\":1,\n" +
                "    \"product_name\":null,\n" +
                "    \"is_urge\":1,\n" +
                "    \"stages_num\":1,\n" +
                "    \"expire_level\":\"3\",\n" +
                "    \"user_id\":397139,\n" +
                "    \"org_id\":14,\n" +
                "    \"apply_time_text\":\"\",\n" +
                "    \"admin_id\":532,\n" +
                "    \"loan_term\":5,\n" +
                "    \"sync_status\":0,\n" +
                "    \"orders\":{\n" +
                "        \"id\":116962,\n" +
                "        \"order_no\":\"2207221432335698\",\n" +
                "        \"merchant_id\":5,\n" +
                "        \"merchant_name\":\"Much Rupee\",\n" +
                "        \"product_id\":10,\n" +
                "        \"product_thumb\":\"https:\\/\\/jituloan.s3.ap-south-1.amazonaws.com\\/system\\/20220629\\/ec02a3c4d2693de8877da59b7858f0cc7.png\",\n" +
                "        \"product_name\":\"Much Rupee\",\n" +
                "        \"user_id\":397139,\n" +
                "        \"package_name\":\"com.cash.daily.loan\",\n" +
                "        \"channel_name\":\"default\",\n" +
                "        \"app_version\":\"1.0.1\",\n" +
                "        \"realname\":\"Parmeshwar Ganesh\",\n" +
                "        \"mobile\":\"9975244410\",\n" +
                "        \"identity_no\":\"348245200779\",\n" +
                "        \"pan_no\":\"JPBPS1384L\",\n" +
                "        \"user_bank\":\"157225\",\n" +
                "        \"bank_name\":null,\n" +
                "        \"card_no\":\"196701515105\",\n" +
                "        \"pay_id\":null,\n" +
                "        \"risk_id\":null,\n" +
                "        \"risk_no\":\"0\",\n" +
                "        \"risk_status\":0,\n" +
                "        \"payout_id\":72834,\n" +
                "        \"payin_id\":null,\n" +
                "        \"order_ip\":\"106.210.226.170\",\n" +
                "        \"login_id\":null,\n" +
                "        \"local_x\":null,\n" +
                "        \"local_y\":null,\n" +
                "        \"loan_term\":5,\n" +
                "        \"term_unit\":\"days\",\n" +
                "        \"urge_days\":0,\n" +
                "        \"loan_amount\":\"6000.00\",\n" +
                "        \"service_rate\":0.42,\n" +
                "        \"service_amount\":\"2520.00\",\n" +
                "        \"interest_rate\":0,\n" +
                "        \"interest_amount\":\"0.00\",\n" +
                "        \"delay_rate\":0.4,\n" +
                "        \"expire_rate\":0.08,\n" +
                "        \"arrival_amount\":\"3480.00\",\n" +
                "        \"repayment_amount\":\"6000.00\",\n" +
                "        \"stages_count\":1,\n" +
                "        \"stages_num\":0,\n" +
                "        \"stages_days\":null,\n" +
                "        \"is_renewal\":1,\n" +
                "        \"is_renewaled\":0,\n" +
                "        \"is_reloan\":1,\n" +
                "        \"check_time\":1658480821,\n" +
                "        \"is_audit\":1,\n" +
                "        \"is_auto\":0,\n" +
                "        \"is_loan\":1,\n" +
                "        \"loan_time\":1658482933,\n" +
                "        \"expire_date\":1658860200,\n" +
                "        \"risk_order\":1,\n" +
                "        \"risk_result\":\"1\",\n" +
                "        \"risk_sub\":0,\n" +
                "        \"sync_status\":1,\n" +
                "        \"sync_msgs\":\"\",\n" +
                "        \"status\":180,\n" +
                "        \"remark\":null,\n" +
                "        \"createtime\":1658480553,\n" +
                "        \"updatetime\":1658482933,\n" +
                "        \"createtime_text\":\"22\\/07\\/2022 14:32:33\",\n" +
                "        \"apply_time_text\":\"22\\/07\\/2022 14:32:33\",\n" +
                "        \"check_time_text\":\"22\\/07\\/2022 14:37:01\",\n" +
                "        \"loan_time_text\":\"22\\/07\\/2022 15:12:13\",\n" +
                "        \"term_unit_text\":\"days\",\n" +
                "        \"status_text\":\"Overdue\"\n" +
                "    },\n" +
                "    \"status_text\":\"Overdue\",\n" +
                "    \"repay_amount\":\"6000.00\",\n" +
                "    \"order_id\":116962,\n" +
                "    \"status\":\"180\",\n" +
                "    \"order_no\":\"2207221432335698\",\n" +
                "    \"sync_msgs\":null,\n" +
                "    \"expire_rate\":0.08,\n" +
                "    \"expire_days\":1,\n" +
                "    \"remark\":null,\n" +
                "    \"merchant_id\":5,\n" +
                "    \"expire_time_text\":\"27\\/07\\/2022 00:00:00\",\n" +
                "    \"products\":{\n" +
                "        \"id\":10,\n" +
                "        \"merchant_id\":5,\n" +
                "        \"product_name\":\"Much Rupee\",\n" +
                "        \"product_image\":\"https:\\/\\/jituloan.s3.ap-south-1.amazonaws.com\\/system\\/20220629\\/ec02a3c4d2693de8877da59b7858f0cc7.png\",\n" +
                "        \"product_images\":null,\n" +
                "        \"type_id\":null,\n" +
                "        \"cate_id\":null,\n" +
                "        \"link\":null,\n" +
                "        \"product_desc\":null,\n" +
                "        \"apply_condition\":null,\n" +
                "        \"amount_range\":\"5,000-50,000\",\n" +
                "        \"interest_range\":\"0.01 - 0.1% \\/ day\",\n" +
                "        \"term_range\":\"91- 365 days\",\n" +
                "        \"show_type\":\"normal\",\n" +
                "        \"risk_score_min\":null,\n" +
                "        \"risk_score_max\":null,\n" +
                "        \"risk_result\":\"1,2,3,4,5\",\n" +
                "        \"loan_config\":null,\n" +
                "        \"urge_days\":0,\n" +
                "        \"loan_term\":5,\n" +
                "        \"term_unit\":\"days\",\n" +
                "        \"loan_amount\":\"2000.00\",\n" +
                "        \"impure_amount\":\"5000.00\",\n" +
                "        \"loan_limit\":\"15000.00\",\n" +
                "        \"loan_lift\":\"2000.00\",\n" +
                "        \"interest_rate\":0,\n" +
                "        \"service_rate\":0.45,\n" +
                "        \"lift_service_rate\":\"{\\\"1\\\":\\\"0.42\\\",\\\"2\\\":\\\"0.42\\\",\\\"3\\\":\\\"0.42\\\",\\\"4\\\":\\\"0.40\\\",\\\"5\\\":\\\"0.40\\\",\\\"6\\\":\\\"0.40\\\"}\",\n" +
                "        \"delay_rate\":0.4,\n" +
                "        \"expire_rate\":0.08,\n" +
                "        \"stages_count\":null,\n" +
                "        \"stages_days\":null,\n" +
                "        \"is_renewal\":1,\n" +
                "        \"delay_expire\":1,\n" +
                "        \"is_top\":0,\n" +
                "        \"sort\":10,\n" +
                "        \"model\":null,\n" +
                "        \"star_number\":null,\n" +
                "        \"is_audit_0\":null,\n" +
                "        \"is_audit_1\":null,\n" +
                "        \"is_audit_nums\":0,\n" +
                "        \"page_expire\":30,\n" +
                "        \"status\":\"normal\",\n" +
                "        \"createtime\":1656488926,\n" +
                "        \"updatetime\":1658472234,\n" +
                "        \"show_type_text\":\"Normal\",\n" +
                "        \"term_unit_text\":\"days\",\n" +
                "        \"status_text\":\"Normal\"\n" +
                "    },\n" +
                "    \"service_amount\":\"0.00\",\n" +
                "    \"stages_count\":null,\n" +
                "    \"repay_time_text\":\"\",\n" +
                "    \"service_rate\":0,\n" +
                "    \"calculate_expire_time\":1658946600,\n" +
                "    \"arrival_amount\":\"0.00\",\n" +
                "    \"createtime\":1658482933,\n" +
                "    \"expire_amount\":\"480.00\",\n" +
                "    \"repay_time\":0,\n" +
                "    \"is_renewal\":1,\n" +
                "    \"is_renewaled\":0,\n" +
                "    \"risk_detail\":1,\n" +
                "    \"payin_id\":null,\n" +
                "    \"updatetime\":1658975659,\n" +
                "    \"user\":{\n" +
                "        \"id\":397139,\n" +
                "        \"group_id\":0,\n" +
                "        \"adid\":\"defd7c671a019cb7c1952e3d5d914946\",\n" +
                "        \"androidId\":\"d294c5d5606bf27c\",\n" +
                "        \"app_name\":\"Daily Loan\",\n" +
                "        \"app_version\":\"1.0.1\",\n" +
                "        \"package_name\":\"com.cash.daily.loan\",\n" +
                "        \"channel_name\":\"default\",\n" +
                "        \"channel_guiin\":\"{\\\"adgroup\\\":\\\"\\\",\\\"adid\\\":\\\"defd7c671a019cb7c1952e3d5d914946\\\",\\\"campaign\\\":\\\"\\\",\\\"clickLabel\\\":\\\"\\\",\\\"costAmount\\\":\\\"NaN\\\",\\\"costCurrency\\\":\\\"\\\",\\\"costType\\\":\\\"\\\",\\\"creative\\\":\\\"\\\",\\\"network\\\":\\\"Unattributed\\\",\\\"trackerName\\\":\\\"Unattributed\\\",\\\"trackerToken\\\":\\\"unattr\\\"}\",\n" +
                "        \"username\":\"9975244410\",\n" +
                "        \"nickname\":\"9975244410\",\n" +
                "        \"mobile\":\"9975244410\",\n" +
                "        \"realname\":\"Parmeshwar Ganesh\",\n" +
                "        \"gender\":\"Male\",\n" +
                "        \"birthday\":\"01\\/01\\/1993\",\n" +
                "        \"identity_no\":\"348245200779\",\n" +
                "        \"pan_no\":\"JPBPS1384L\",\n" +
                "        \"email\":\"\",\n" +
                "        \"password\":\"0d193ab4d582b2041c3c1db8218d8975\",\n" +
                "        \"salt\":\"Tv1oMh\",\n" +
                "        \"avatar\":\"data:image\\/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgaGVpZ2h0PSIxMDAiIHdpZHRoPSIxMDAiPjxyZWN0IGZpbGw9InJnYigyMDAsMTYwLDIyOSkiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48L3JlY3Q+PHRleHQgeD0iNTAiIHk9IjUwIiBmb250LXNpemU9IjUwIiB0ZXh0LWNvcHk9ImZhc3QiIGZpbGw9IiNmZmZmZmYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHRleHQtcmlnaHRzPSJhZG1pbiIgZG9taW5hbnQtYmFzZWxpbmU9ImNlbnRyYWwiPjk8L3RleHQ+PC9zdmc+\",\n" +
                "        \"level\":1,\n" +
                "        \"bio\":\"\",\n" +
                "        \"money\":\"0.00\",\n" +
                "        \"score\":0,\n" +
                "        \"successions\":1,\n" +
                "        \"maxsuccessions\":1,\n" +
                "        \"prevtime\":1658068558,\n" +
                "        \"logintime\":1658473304,\n" +
                "        \"loginip\":\"49.248.126.134\",\n" +
                "        \"loginfailure\":0,\n" +
                "        \"joinip\":\"110.227.11.63\",\n" +
                "        \"jointime\":1658068558,\n" +
                "        \"createtime\":1658068558,\n" +
                "        \"updatetime\":1658551045,\n" +
                "        \"token\":\"\",\n" +
                "        \"status\":\"normal\",\n" +
                "        \"old\":0,\n" +
                "        \"verification\":{\n" +
                "            \"email\":0,\n" +
                "            \"mobile\":0\n" +
                "        },\n" +
                "        \"apply_flag\":1,\n" +
                "        \"apply_nums\":4,\n" +
                "        \"risk_user\":1,\n" +
                "        \"risk_result\":2,\n" +
                "        \"risk_time\":1658069174,\n" +
                "        \"risk_sub\":0,\n" +
                "        \"onekey_close\":0,\n" +
                "        \"url\":\"\\/u\\/397139\",\n" +
                "        \"createtime_text\":\"2022-07-17 20:05:58\"\n" +
                "    }\n" +
                "}";
        Any orderInfo = JsonIterator.deserialize(detail);

        String appName = orderInfo.get("user").get("app_name")+"["+orderInfo.get("orders").get("product_name").toString()+"]";

        LOGGER.info("==value==,value:{}", appName);
    }
}
